package ks.app.smartDic;

import java.io.InputStream;

import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

public class jerichoParser {

	public String pronunciation;
	public String header;
	Source source;
	String query;

	jerichoParser() {

	}

	jerichoParser(String pQuery) {

		query = pQuery;
	}

	public String parseDefinition(InputStream data) {

		StringBuilder sb = new StringBuilder();

		try {
			source = new Source(data);

			Element box = source.getElementById("ct");
			Element pronunciation = box.getFirstElementByClass("fz11 tx3");
			Element definition = box.getFirstElementByClass("dc1");

			Element header = definition.getFirstElementByClass("dht1");
			Element li_tag = source.getFirstElementByClass("li2 ol_tag");

			List<Element> li_list = li_tag.getChildElements();

			int i = 1;

			for (Element e : li_list) {

				if (i == 1) {
					sb.append("<font><h1>* ");
					sb.append("뜻");
					sb.append("</h1></font>");
					sb.append("<br />");

					if (pronunciation != null)
						sb.append("발음 : " + pronunciation.toString() + "<br />");

					if (header != null)
						sb.append(header.toString());
				}

				sb.append(i + ". "
						+ e.getFirstElement("dt").getTextExtractor().toString()
						+ "<br /> <br />");
				i++;
			}

		} catch (Exception e) {
			ksLog.d("goParseError", e.getMessage());
		}

		if (sb.length() == 0) {

			try {

				List<Element> titleList = source.getAllElementsByClass("dht4f");

				Element li_tag = source.getFirstElementByClass("li3");
				List<Element> li_list = li_tag.getChildElements();

				int i = 0;
				for (Element e : li_list) {

					if (i == 0) {

						try {
							sb.append("<font><h1>* ");
							String title = titleList.get(i).getTextExtractor()
									.toString();
							title = title.substring(0, title.indexOf("("));
							sb.append(title);
							sb.append("</h1></font>");
							sb.append("<br />");
						} catch (Exception exception) {
						}
												
						Element pronunciation = source.getFirstElementByClass("fz12 tx8");
						if(pronunciation != null)
							sb.append("<br /> 발음 : " + pronunciation.toString() + "<br /> <br />");
						
						i++;
					}

					if (e.getFirstElementByClass("tx6") != null) {
						sb.append("<b>");
						sb.append(e.getFirstElementByClass("tx6")
								.getTextExtractor() + "<br />");
						sb.append("</b>");
					}

					if (e.getFirstElementByClass("tt1") != null) {
						sb.append(e.getFirstElementByClass("tt1")
								.getTextExtractor() + "<br />");
					}

					if (e.getFirstElementByClass("te1") != null) {

						sb.append(e.getFirstElementByClass("te1")
								.getTextExtractor() + "<br />");

					}
					if (e.getFirstElementByClass("tk1") != null) {
						sb.append(e.getFirstElementByClass("tk1")
								.getTextExtractor());
					}

					sb.append("<br /><br />");
				}

			} catch (Exception e) {

				ksLog.d("error", e.getMessage());
			}
		}

		if (sb.length() == 0) {

			try {

				sb.append(getEngAutoCorrection());

			} catch (Exception e) {

				ksLog.d("error", e.getMessage());
			}
		}

		return sb.toString().replace(query, "<b>" + query + "</b>");
	}

	public String getMP3Url(InputStream data) {
		try {

			Source source = new Source(data);
			Element mp3Element = source.getFirstElementByClass("play3");
			
			if (mp3Element == null)
				return source.getFirstElementByClass("sbt3").getAttributeValue(
						"href");
			else
				return mp3Element.getAttributeValue("playlist");

		} catch (Exception e) {

		}

		return null;
	}

	public String parseWord(InputStream data) {

		StringBuilder sb = new StringBuilder();

		try {

			source = new Source(data);

			Element li_tag = source.getFirstElementByClass("li3");
			if (li_tag != null) {
				List<Element> li_list = li_tag.getChildElements();

				int i = 0;
				for (Element e : li_list) {
					if (i++ == 0) {
						sb.append("<font><h1>* ");
						sb.append(source.getFirstElementByClass("nv1")
								.getFirstElementByClass("on")
								.getTextExtractor().toString());
						sb.append("</h1></font>");
						sb.append("<br />");
					}

					sb.append(i + ". ");
					sb.append("<b><font color=\"#0068b1\">");
					sb.append(e.getFirstElementByClass("tx6")
							.getTextExtractor() + "<br />");
					sb.append("</font></b>");

					if (e.getFirstElementByClass("tt1") != null)
						sb.append(e.getFirstElementByClass("tt1")
								.getTextExtractor() + "<br />");
					if (e.getFirstElementByClass("te1") != null)
						sb.append(e.getFirstElementByClass("te1")
								.getTextExtractor() + "<br />");
					if (e.getFirstElementByClass("tk1") != null)
						sb.append(e.getFirstElementByClass("tk1")
								.getTextExtractor());

					sb.append("<br /><br />");

				}
			}

			if (sb.length() == 0) {

				try {

					sb.append(getEngAutoCorrection());

				} catch (Exception e) {

					ksLog.d("error", e.getMessage());
				}
			}

		} catch (Exception e) {
			ksLog.d("parseWordErr", e.getMessage());
		}

		return sb.toString().replace(query, "<b>" + query + "</b>");
	}

	public String parseExample(InputStream data) {

		StringBuilder sb = new StringBuilder();
		try {

			source = new Source(data);

			Element li_tag = source.getFirstElementByClass("li3");
			if (li_tag != null) {
				List<Element> li_list = li_tag.getChildElements();

				int i = 0;
				for (Element e : li_list) {
					if (i++ == 0) {
						sb.append("<font><h1>* ");
						sb.append("예문");
						sb.append("</h1></font>");
						sb.append("<br />");
					}

					sb.append(i + ". ");
					if (e.getFirstElementByClass("te1") != null)
						sb.append(e.getFirstElementByClass("te1")
								.getTextExtractor() + "<br />");
					if (e.getFirstElementByClass("tk1") != null)
						sb.append(e.getFirstElementByClass("tk1")
								.getTextExtractor() + "<br />");

					sb.append("<br />");

				}
			}
			if (sb.length() == 0) {

				try {

					sb.append(getEngAutoCorrection());

				} catch (Exception e) {

					ksLog.d("error", e.getMessage());
				}
			}

		} catch (Exception e) {

			ksLog.d("exception", e.getMessage());
		}

		return sb.toString().replace(query, "<b>" + query + "</b>");
	}

	public String parseSynonum(InputStream data) {

		StringBuilder sb = new StringBuilder();

		try {

			source = new Source(data);

			List<Element> header = source.getAllElementsByClass("dht3");
			if (header != null) {
				List<Element> content_li_list = source
						.getAllElementsByClass("li4");

				int i = 0;
				for (Element e : header) {
					if (i == 0) {
						sb.append("<font><h1>* ");
						sb.append("유의어·반의어");
						sb.append("</h1></font>");
						sb.append("<br />");
					}

					sb.append((i + 1) + ". ");
					sb.append("<font color=\"#0068b1\"><b>");
					sb.append(e.getTextExtractor().toString() + "<br /> <br />");
					sb.append("</b></font>");

					int j = 1;
					for (Element liElement : content_li_list.get(i++)
							.getChildElements()) {

						sb.append(i + "-" + (j++) + ". ");
						sb.append("<b>"
								+ liElement.getTextExtractor().toString()
								+ "</b>" + "<br /> <br />");

					}

				}
			}
			if (sb.length() == 0) {

				try {

					sb.append(getEngAutoCorrection());

				} catch (Exception e) {

					ksLog.d("error", e.getMessage());
				}
			}

		} catch (Exception e) {
			ksLog.d("synonum exception", e.getMessage());
		}

		return sb.toString();

	}

	public String parseOnlyEngDefinition(InputStream data) {

		StringBuilder sb = new StringBuilder();

		try {

			source = new Source(data);

			String sb1 = "", sb2 = "";
			sb1 = addMeaning("box_wrap1", "dic_tit6", "mean_on");
			sb2 = addMeaning("box_wrap20", "dic_tit6", "mean_on");

			if (sb1 != null || sb2 != null) {
				sb.append("<font><h1>* ");
				sb.append("뜻 ");
				sb.append("</h1></font>");
				sb.append("<br />");
			}

			if (sb1 != null)
				sb.append(sb1);
			if (sb2 != null)
				sb.append(sb2);

		} catch (Exception e) {
			ksLog.d("e", e.getMessage());
		}

		if (sb.length() == 0) {
			try {
				Element resultContent = source.getFirstElementByClass("blue01");

				if (resultContent != null) {
					sb.append(TextBoxValidator.removeReturn(query)
							+ "에 해당하는 검색 결과가 없습니다.");
					sb.append("<br /> <br />");
					sb.append("혹시 원하시는 단어가 ");
					sb.append("<font color=\"#0068b1\">");
					sb.append(source.getFirstElementByClass("blue01")
							.getTextExtractor().toString());
					sb.append("</font>");
					sb.append("입니까?");
				}
			} catch (Exception e) {
				ksLog.d("recommand exception");
			}

		}

		return sb.toString();

	}

	private String addMeaning(String boxClassName, String titleClasName,
			String meaningClassName) {
		String sb;

		List<Element> box = source.getAllElementsByClass(boxClassName);
		for (Element e : box) {
			Element titleList = e.getFirstElementByClass(titleClasName);
			List<Element> meaning = e.getAllElementsByClass(meaningClassName);

			sb = null;
			if (titleList != null)
				sb = titleList.getTextExtractor().toString() + "<br /><br />";

			for (Element e2 : meaning)
				sb += e2.getTextExtractor().toString() + "<br /><br />";

			if (sb != null)

				return sb;
		}
		return null;

	}

	public String parseOnlyEngWord(InputStream data) {

		String sb = "";

		try {

			source = new Source(data);

			Element list = source.getFirstElementByClass("list_e4");
			List<Element> definitionList = list
					.getAllElementsByClass("fnt_e01");
			List<Element> exampleList = list.getAllElements("dd");

			int i = 0;
			for (Element e : definitionList) {
				if (i == 0) {
					sb += ("<font><h1>* ");
					sb += "단어·숙어";
					sb += ("</h1></font>");
				}
				sb += (i + 1) + ". ";
				sb += e.getTextExtractor().toString() + "<br /><br />";

				List<Element> smallExampleFragments = exampleList.get(i++)
						.getAllElementsByClass("fnt_e07");

				for (Element e2 : smallExampleFragments) {
					sb += e2.getTextExtractor().toString() + "<br /><br />";
				}

			}

		} catch (Exception e) {
			ksLog.d("e", e.getMessage());
		}

		if (sb.length() == 0) {
			try {
				Element resultContent = source.getFirstElementByClass("blue01");

				if (resultContent != null) {
					sb += (TextBoxValidator.removeReturn(query) + "에 해당하는 검색 결과가 없습니다.");
					sb += ("<br /> <br />");
					sb += ("혹시 원하시는 단어가 ");
					sb += ("<font color=\"#0068b1\">");
					sb += (source.getFirstElementByClass("blue01")
							.getTextExtractor().toString());
					sb += ("</font>");
					sb += ("입니까?");
				}
			} catch (Exception e) {
				ksLog.d("recommand exception");
			}

		}

		return sb.replace(query, "<b>" + query + "</b>");

	}

	public String parseKorDefinition(InputStream data, String word) {

		String bigClassName = null;
		String className = null;
		String sb = "";

		if (word.compareTo("단어") == 0) {
			bigClassName = "section";
			className = "head_word";
		} else if (word.compareTo("속담/관용구") == 0) {
			bigClassName = "section";
			className = "head_adage";
		} else if (word.compareTo("본문") == 0) {
			bigClassName = "section4";
			className = "head_main";
		} else if (word.compareTo("예문") == 0) {
			bigClassName = "section";
			className = "head_ex";
		} else if (word.compareTo("맞춤법/표기법") == 0) {
			bigClassName = "section4";
			className = "head_study";
		}

		try {
			source = new Source(data);

			List<Element> selectionList = source
					.getAllElementsByClass(bigClassName);

			if (word.compareTo("맞춤법/표기법") != 0) {

				for (Element e : selectionList) {

					if (e.getFirstElementByClass("head")
							.getFirstElementByClass(className) != null) {

						if (e.getFirstElementByClass("lst3").getChildElements() != null) {

							List<Element> liList = e.getFirstElementByClass(
									"lst3").getChildElements();

							int i = 0;
							for (Element e2 : liList) {

								if (i++ == 0) {
									sb += getHeader(word);
								}

								if (word.compareTo("단어") == 0
										|| word.compareTo("속담/관용구") == 0) {

									if (e2.getFirstElement("div")
											.getFirstElement("a") != null) {
										sb += (i) + ". ";
										sb += e2.getFirstElement("div")
												.getFirstElement("a")
												.getTextExtractor().toString()
												+ "<br /><br />";
									}
									List<Element> pTagList = e2
											.getAllElements("p");
									for (Element e3 : pTagList) {
										sb += e3.getTextExtractor().toString();
									}
								} else if (word.compareTo("본문") == 0) {

									if (e2.getFirstElement("div")
											.getFirstElement("a") != null) {
										sb += (i) + ". ";
										sb += e2.getFirstElement("div")
												.getFirstElement("a")
												.getTextExtractor().toString()
												+ "<br /><br />";
									}

									List<Element> liTagList = e2
											.getFirstElement("ul")
											.getChildElements();

									for (Element e3 : liTagList) {
										sb += e3.getTextExtractor().toString()
												+ "<br />";
									}

								} else if (word.compareTo("예문") == 0) {
									if (e2.getFirstElement("p") != null) {
										sb += (i) + ". ";
										sb += e2.getFirstElement("p")
												.getTextExtractor().toString()
												+ "<br />";
									}
								}

								sb += "<br /> <br />";
							}

							break;
						}
					}

				}
			} else {
				Element sign = source
						.getFirstElementByClass("lst_study lst_studysearch");

				List<Element> dtList = sign.getAllElements("dt");
				int i = 0;
				for (Element e : dtList) {
					sb += (i + 1) + ". ";
					sb += e.getFirstElement("a").getTextExtractor().toString();
					sb += "&nbsp;";
					sb += "(";
					sb += e.getFirstElement("span").getTextExtractor()
							.toString();
					sb += ")";
					sb += "<br />";
					sb += sign.getAllElements("dd").get(i++).getTextExtractor()
							.toString();
					sb += "<br /><br />";
				}

			}

		} catch (Exception e) {
			ksLog.d("kor exception", e.getMessage());
			// return sb;
		}

		if (sb.length() == 0) {

			try {
				Element result = source.getFirstElementByClass("result");
				Element resultContent = result.getFirstElement("a");

				if (result != null && resultContent != null) {
					sb += TextBoxValidator.removeReturn(query)
							+ "에 해당하는 검색 결과가 없습니다.";
					sb += "<br /> <br />";
					sb += "혹시 원하시는 단어가 ";
					sb += "<font color=\"#0068b1\">";
					sb += resultContent.getTextExtractor().toString();
					sb += ("</font>");
					sb += "입니까?";
				}
			} catch (Exception e) {
				ksLog.d("recommand exception");
			}
		}

		return sb
				.replace(query, "<font color=\"#0068b1\">" + query + "</font>");

	}

	private String getHeader(String pString) {
		String sb = "";

		sb += ("<font><h1>* ");
		sb += pString;
		sb += ("</h1></font>");

		return sb;
	}

	private String getEngAutoCorrection() {
		StringBuilder sb = new StringBuilder();

		Element recommandList = source.getFirstElementByClass("li4t");

		if (recommandList != null) {

			sb.append(TextBoxValidator.removeReturn(query) + "에 해당하는 단어가 없습니다.");
			sb.append("<br /> <br /><br />");
			sb.append("단어의 <font color=\"#e51313\">철자를 자동으로 변환</font>한 결과입니다.");
			sb.append("<br /><br />");

		}

		for (Element e : recommandList.getChildElements()) {

			Element aLink = e.getFirstElement("a");

			sb.append("<font color=\"#0068b1\">");
			sb.append(aLink.getTextExtractor().toString());
			sb.append("</font> ");

			Element span = e.getFirstElementByClass("fz12 tx7");
			sb.append(span.getTextExtractor().toString());

			sb.append("<br />");
		}

		return sb.toString();
	}
}
